<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row>
        <el-form
          label-position="right"
          :model="listQuery"
          label-width="100px"
        >

          <el-col :span="8">
            <el-form-item
              label="参考工资月份："
              label-width="auto"
            >
              <el-select
                v-model="listQuery.salaryMonth"
                :disabled="thirteenExist"
                class="filter-item"
                placeholder="--请选择--"
                @change="change"
              >
                <el-option
                  v-for="item in salaryMonth"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="工资项：">
              <el-select
                v-model="listQuery.selectSalaryItem"
                :disabled="thirteenExist"
                class="filter-item only-one-row"
                multiple
                placeholder="--请选择--"
              >
                <template v-for="item in salaryItem">
                  <el-option
                    v-if="item.columnName !== 's1' && item.columnName !== 's2' "
                    :key="item.columnName"
                    :label="item.salaryName"
                    :value="item.columnName"
                  />
                </template>
              </el-select>
            </el-form-item>
          </el-col>

        </el-form>

        <el-col
          :span="8"
          style="text-align: right;"
        >
          <el-button
            v-if="!thirteenExist"
            size="small"
            class="filter-item"
            type="primary"
            style="width: auto; margin-left: 10px;"
            @click="generate"
          >
            生成十三月工资
          </el-button>
          <el-button
            v-if="thirteenExist"
            size="small"
            class="filter-item"
            type="primary"
            style="width: auto; margin-left: 10px;"
            :loading="regenerateBtnLoading"
            @click="regenerate"
          >
            重新生成
          </el-button>
          <el-button
            v-if="!thirteenExist"
            size="small"
            class="filter-item"
            type="primary"
            style="margin-left: 10px;"
            :loading="saveBtnLoading"
            @click="save"
          >
            保存
          </el-button>
          <el-button
            v-if="thirteenExist"
            size="small"
            class="filter-item"
            type="primary"
            style="margin-left: 10px;"
            :loading="editBtnLoading"
            @click="edit"
          >
            保存修改
          </el-button>
          <el-button
            v-if="!thirteenExist"
            size="small"
            class="filter-item"
            type="primary"
            style="margin-left: 10px;"
            @click="cancel"
          >
            取消
          </el-button>
          <el-button
            size="small"
            class="filter-item"
            type="primary"
            style="margin-left: 10px;"
          >
            附件
          </el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 表格部分 -->
    <el-table
      v-if="tableShow"
      ref="singleTable"
      v-loading="listLoading"
      :data="list"
      :stripe="true"
      fit
      :height="tableHeight"
      style="width: 100%;"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column
        lable=""
        prop="index"
        align="center"
        width="80"
        fixed
      />
      <el-table-column
        label="工资月份"
        prop="salaryMonth"
        align="center"
        fixed
      />
      <el-table-column
        label="科室"
        prop="deptId"
        align="center"
        fixed
      >
        <template slot-scope="{row}">
          <span>{{ row.deptId | deptNameFilter(that) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="身份证号"
        prop="idenNo"
        align="center"
        min-width="180"
        fixed
      />
      <el-table-column
        label="姓名"
        align="center"
        fixed
      >
        <template slot-scope="{row}">
          <el-link
            type="primary"
            @click="viewInfo(row)"
          >
            <span>{{ row.personName }}</span>
          </el-link>
        </template>
      </el-table-column>
      <!--<el-table-column :label=" 's2' | salaryNameFilter(that) " align="center" min-width="150" fixed>-->
      <!--<template slot-scope="{row}">-->
      <!--<div style="float: right;">-->
      <!--<el-input-->
      <!--v-if="row.index !== '合计' && isSubmitInAgency !== 1 "-->
      <!--v-model="row['s2']"-->
      <!--@change="handleChange($event, row, 's2')"-->
      <!--@input="handleInput($event, row, 's2')"-->
      <!--/>-->
      <!--<span v-else>{{ Number(row['s2']).toFixed(2) }}</span>-->
      <!--</div>-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column
        :label=" 's1' | salaryNameFilter(that) "
        align="center"
        min-width="150"
        fixed
      >
        <template slot-scope="{row}">
          <div style="float: right;">
            <el-input
              v-if="row.index !== '合计' && isSubmitInAgency !== 1 "
              v-model="row['s1']"
              maxlength="10"
              @change="handleChange($event, row, 's1')"
              @input="handleInput($event, row, 's1')"
            />
            <span v-else>{{ Number(row['s1']).toFixed(2) }}</span>
          </div>
        </template>
      </el-table-column>
      <template v-for="item in column">
        <el-table-column
          v-if="item !== 's1' && item !== 's2' "
          :key="item"
          :label="item | salaryNameFilter(that)"
          align="center"
          min-width="150"
        >
          <template slot-scope="{row}">
            <div style="float: right;">
              <span>{{ Number(row[item]).toFixed(2) }}</span>
            </div>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <!--分页部分-->
    <!--<pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList"/>-->
    <PersonSalaryInfo ref="personSalaryInfo" />
  </div>
</template>

<script>
import {
  queryHistoryMonthList,
  queryColumnByAgencyIdAndSalaryMonth,
  querySalaryHistoryPage,
  saveThirteenthMonthSalary,
  queryThirteenSalaryPage,
  queryColumnByAgencyId,
  physicalDeleteThirteenMonthSalary,
  submitThirteenthMonthSalary
} from '@/api/unitSalaryReport/thirteenthMonthSalary'
import { getDepartmentList } from '@/api/unitInformationMaintenance/internalOrganizationMaintenance'
import { queryAgencyNameAndState } from '@/api/unitInformationMaintenance/unitInformationEdit'
// import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import PersonSalaryInfo from '@/components/personSalaryInfo/personSalaryInfo'

export default {
  name: 'ThirteenthMonthSalary',
  components: { tableEmpty, PersonSalaryInfo },
  filters: {
    salaryNameFilter(value, that) {
      const salaryItem = that.salaryItem
      for (const item of salaryItem) {
        if (value === item.columnName) {
          return item.salaryName
        }
      }
    },
    deptNameFilter(value, that) {
      const deptNames = that.deptNames
      for (const item of deptNames) {
        if (value === item.code) {
          return item.name
        }
      }
    }
  },
  data() {
    return {
      tableHeight: null,
      that: this,
      tableShow: false,
      listLoading: false,
      regenerateBtnLoading: false,
      saveBtnLoading: false,
      editBtnLoading: false,
      thirteenExist: false,
      list: [],
      deptNames: [],
      // total: 0,
      listQuery: {
        // page: 1,
        // limit: 10,
        agencyId: this.$store.getters.userInfo.agencyId,
        // agencyId: '1B32807D22F34A5DB12FCEDC8FE6DAF4',
        salaryMonth: '',
        selectSalaryItem: [],
        salaryItem: ''
      },
      column: [],
      salaryMonth: [],
      salaryItem: [],
      changeMap: {},
      inputMap: {},
      agencyName: '',
      isSubmitInAgency: 1,
      salaryVerifiedInAgencyCode: '1'
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  created() {
    this.initDict()
    this.handleFilter()
  },
  methods: {
    handleFilter() {
      this.queryAgencyNameAndState()
      this.getColumnByAgencyId()
      this.getThirteenSalaryList()
    },
    // 查询审核和送审状态
    queryAgencyNameAndState() {
      return queryAgencyNameAndState(this.listQuery.agencyId)
        .then(res => {
          this.agencyName = res.data.agencyName
          this.isSubmitInAgency = res.data.isSubmitInAgency
          this.salaryVerifiedInAgencyCode = res.data.salaryVerifiedInAgencyCode
        })
        .catch(() => {
          this.agencyName = ''
          this.isSubmitInAgency = 1
          this.salaryVerifiedInAgencyCode = '1'
        })
    },

    getColumnByAgencyId() {
      queryColumnByAgencyId(this.listQuery.agencyId).then(res => {
        this.salaryItem = res.data
        this.column = []
        for (const item of this.salaryItem) {
          this.column.push(item.columnName)
        }
      })
    },
    getThirteenSalaryList() {
      this.listLoading = true
      queryThirteenSalaryPage(this.listQuery.agencyId).then(res => {
        this.list = res.data
        if (this.list.length > 0) {
          this.thirteenExist = true
          this.tableShow = true
        } else {
          this.thirteenExist = false
          this.tableShow = false
        }
        this.initData()
      })
    },

    // 初始化字典
    initDict() {
      // 获取月份
      queryHistoryMonthList(this.listQuery.agencyId).then(res => {
        this.salaryMonth = res.data
      })
      // 查询部门名称
      getDepartmentList({ agencyId: this.listQuery.agencyId }).then(res => {
        this.deptNames = res.data
      })
    },
    // 查询
    getList() {
      this.listLoading = true
      this.listQuery.salaryItem = this.listQuery.selectSalaryItem.join(',')
      this.column = [].concat(this.listQuery.selectSalaryItem)
      querySalaryHistoryPage(this.listQuery).then(res => {
        this.list = res.data
        // this.total = res.data.total;
        if (this.list.length > 0) {
          this.tableShow = true
        } else {
          this.tableShow = false
        }
        this.initData()
      })
    },
    initData() {
      this.changeMap = {}
      this.inputMap = {}
      this.listLoading = false
    },
    generate() {
      this.queryAgencyNameAndState().then(() => {
        if (this.isSubmitInAgency === 1) {
          this.$message({
            message: '单位当月工资已送审，无法生成十三月工资',
            type: 'warning',
            showClose: true,
            duration: 4000
          })
          return
        }
        if (
          this.listQuery.salaryMonth &&
          this.listQuery.selectSalaryItem.length > 0
        ) {
          // this.listQuery.page = 1;
          // this.listQuery.limit = 10;
          this.getList()
        } else {
          this.$message({
            message: '请先选择参考工资月份和工资项',
            type: 'warning',
            showClose: true,
            duration: 4000
          })
        }
      })
    },
    regenerate() {
      this.regenerateBtnLoading = true
      this.queryAgencyNameAndState()
        .then(() => {
          if (this.isSubmitInAgency === 1) {
            this.$message({
              message: '单位当月工资已送审，无法重新生成',
              type: 'warning',
              showClose: true,
              duration: 4000
            })
            this.regenerateBtnLoading = false
            return
          }
          // this.$confirm('确定重新生成吗？', '提示', {
          //   closeOnClickModal: false,
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // })
          //   .then(() => {
          physicalDeleteThirteenMonthSalary(this.listQuery.agencyId)
            .then(res => {
              this.$message({
                message: '删除成功！请再次生成',
                type: 'success',
                showClose: true,
                duration: 4000
              })
              this.regenerateBtnLoading = false
              this.thirteenExist = false
              this.tableShow = false
            })
            .catch(() => {
              this.regenerateBtnLoading = false
            })
        })
        .catch(() => {
          this.regenerateBtnLoading = false
        })
        // })
        // .catch(() => {
        //   this.regenerateBtnLoading = false
        // })
    },
    save() {
      this.saveBtnLoading = true
      if (this.list.length === 0) {
        this.saveBtnLoading = false
        return
      }
      this.queryAgencyNameAndState()
        .then(() => {
          if (this.isSubmitInAgency === 1) {
            this.$message({
              message: '单位当月工资已送审，无法保存',
              type: 'warning',
              showClose: true,
              duration: 4000
            })
            this.saveBtnLoading = false
            return
          }
          // this.$confirm('确定保存吗？', '提示', {
          //   closeOnClickModal: false,
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // })
          //   .then(() => {
          // 保存前获取最新工资名和工资项字段名对应关系
          this.change(this.listQuery.salaryMonth)
            .then(() => {
              // 历史工资项对应当月工资项
              const map = {}
              for (const item of this.salaryItem) {
                map[item.columnName] = item.currentColumn
              }
              // 将历史工资项字段转为当月工资项字段
              const historySalaryItemArr = this.listQuery.salaryItem.split(
                ','
              )
              const currentSalaryItemArr = []
              currentSalaryItemArr.push('s1')
              currentSalaryItemArr.push('s2')
              for (const item of historySalaryItemArr) {
                currentSalaryItemArr.push(map[item])
              }
              const currentsalaryItem = currentSalaryItemArr.join(',')
              const submitList = []
              for (const item of this.list) {
                if (this.list.indexOf(item) !== 0) {
                  const submit = {}
                  submit.agencyId = this.listQuery.agencyId
                  submit.personId = item.personId
                  submit.columnNames = currentsalaryItem
                  submit.s1 = item.s1
                  submit.s2 = item.s2
                  for (const salaryItem of historySalaryItemArr) {
                    submit[map[salaryItem]] = item[salaryItem]
                  }
                  submitList.push(submit)
                }
              }
              saveThirteenthMonthSalary(submitList)
                .then(res => {
                  this.$message({
                    message: '保存成功',
                    type: 'success',
                    showClose: true,
                    duration: 4000
                  })
                  this.handleFilter()
                  this.listQuery.salaryMonth = ''
                  this.listQuery.selectSalaryItem = []
                  this.saveBtnLoading = false
                })
                .catch(() => {
                  this.saveBtnLoading = false
                })
            })
            .catch(() => {
              this.saveBtnLoading = false
            })
        })
        .catch(() => {
          this.saveBtnLoading = false
        })
        // })
        // .catch(() => {
        //   this.saveBtnLoading = false
        // })
    },
    edit() {
      this.editBtnLoading = true
      this.queryAgencyNameAndState()
        .then(() => {
          if (this.isSubmitInAgency === 1) {
            this.$message({
              message: '单位当月工资已送审，无法保存修改',
              type: 'warning',
              showClose: true,
              duration: 4000
            })
            this.editBtnLoading = false
            return
          }
          // this.$confirm('确定修改吗？', '提示', {
          //   closeOnClickModal: false,
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // })
          //   .then(() => {
          for (const item of this.list) {
            item.columnNames = this.column.join(',')
          }
          submitThirteenthMonthSalary(this.list)
            .then(() => {
              this.$message({
                message: '修改成功',
                type: 'success',
                showClose: true,
                duration: 4000
              })
              this.handleFilter()
              this.editBtnLoading = false
            })
            .catch(() => {
              this.editBtnLoading = false
            })
        })
        .catch(() => {
          this.editBtnLoading = false
        })
        // })
        // .catch(() => {
        //   this.editBtnLoading = false
        // })
    },
    cancel() {
      this.listQuery.salaryMonth = ''
      this.listQuery.salaryItem = ''
      this.listQuery.selectSalaryItem = []
      this.column = []
      this.list = []
    },
    change(month) {
      return queryColumnByAgencyIdAndSalaryMonth(
        this.listQuery.agencyId,
        month
      ).then(res => {
        const salaryItem = res.data
        if (salaryItem.length === 0) {
          this.salaryItem = [
            { salaryName: '实发工资', columnName: 's1', currentColumn: 's1' },
            { salaryName: '应发项', columnName: 's2', currentColumn: 's2' }
          ]
        } else {
          this.salaryItem = salaryItem
        }
        this.listQuery.selectSalaryItem = []
      })
    },

    handleInput(val, row, name) {
      const regex = /^\d{0,16}\.?\d{0,2}$/
      if (!regex.test(val)) {
        row[name] = this.inputMap['index' + row.index + '_' + name]
          ? this.inputMap['index' + row.index + '_' + name]
          : '0.00'
      } else {
        this.inputMap['index' + row.index + '_' + name] = val
      }
    },

    handleChange(val, row, name) {
      const regex = /^((0|[1-9][0-9]{0,17})|([0]\.\d{1,2}|[1-9][0-9]{0,15}\.\d{1,2}))$/
      if (!regex.test(val)) {
        row[name] = this.changeMap['index' + row.index + '_' + name]
          ? this.changeMap['index' + row.index + '_' + name]
          : '0.00'
      } else {
        this.changeMap['index' + row.index + '_' + name] = val
      }
    },
    // 查看详情
    viewInfo(currenRow) {
      this.$refs.personSalaryInfo.viewInfo(currenRow.personId, undefined, this.listQuery.agencyId)
    },
    // 获取table高度的方法
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
    },
    /* 重新渲染table组件 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
/** 文本框高度 **/
.el-input:not(.el-pagination__editor):not(.el-input--mini) {
  width: 100px !important;
}

.only-one-row {
  ::v-deep .el-select__tags {
    white-space: nowrap;
    overflow-x: scroll;
    display: inline;

    &::-webkit-scrollbar {
      height: 0;
    }
  }
}
</style>
